package com.webside.play.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webside.enums.ValidateMsg;
import com.webside.play.service.PlayService;
import com.webside.site.mapper.SiteMapper;
import com.webside.site.model.Site;
import com.webside.util.EndecryptUtils;
@Service("playService")
public class PlayServiceImpl implements PlayService {
	@Autowired
	SiteMapper siteMapper;  

	/**
	 * 验证码的组成方式是  appid + key + timestamp 进行md5 32位加密 
	 */
	public String validate(String appid, Long timestamp, String sign) {
		//第一层校验是非空校验
		if (isEmpty(trim(appid))) {
			return ValidateMsg.MISS_APPID.getMsg();
		}else if (timestamp == null) {
			return ValidateMsg.MISS_TIMESTAMP.getMsg();
		}else if (isEmpty(trim(sign))) {
			return ValidateMsg.MISS_SIGN.getMsg();
		}
		
		//第二层校验是过期校验
		Long time = new Date().getTime();
		if ( Math.abs( time - timestamp ) > 300000L ) {
			return ValidateMsg.TIMEOUT.getMsg();
		}
		//第三层是appid有效性的验证
		Site site = siteMapper.findById(appid);
		if (site == null) {
			return ValidateMsg.ERROR_APPID.getMsg();
		}
		
		//第四层验证是key验证
		String key = site.getSecretKey();
		String localStr = appid + key + timestamp;
		String localSign = EndecryptUtils.MD5(localStr);
		if(sign.equals(localSign)){
			return ValidateMsg.ACCESS.getMsg();
		}
		return ValidateMsg.ERROR_SIGN.getMsg();
	}
	/**
	 * 验证码的组成方式是  appid + key + timestamp 进行md5 32位加密 
	 */
	public String validateNoTime(String appid, Long timestamp, String sign) {
		//第一层校验是非空校验
		if (isEmpty(trim(appid))) {
			return ValidateMsg.MISS_APPID.getMsg();
		}else if (timestamp == null) {
			return ValidateMsg.MISS_TIMESTAMP.getMsg();
		}else if (isEmpty(trim(sign))) {
			return ValidateMsg.MISS_SIGN.getMsg();
		}
		
		//第二层是appid有效性的验证
		Site site = siteMapper.findById(appid);
		if (site == null) {
			return ValidateMsg.ERROR_APPID.getMsg();
		}
		
		//第三层验证是key验证
		String key = site.getSecretKey();
		String localStr = appid + key + timestamp;
		String localSign = EndecryptUtils.MD5(localStr);
		if(sign.equals(localSign)){
			return ValidateMsg.ACCESS.getMsg();
		}
		return ValidateMsg.ERROR_SIGN.getMsg();
	}
	
	
	private static boolean isEmpty(String a){
		return a == null || a.length() ==0 ; 
	}
	
	private static String trim(String a){
		if(a == null){
			return null;
		}
		return a.trim();
	}
}
